package com.zoe.sse.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.zoe.sse.service.SSEServer;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

/**
 * @author zoe.Zhang
 * @date 2022/12/30
 * @description
 */
// @CrossOrigin
@RestController
@RequestMapping("/sse")
public class SSEController {


    /**
     * 用于创建连接
     */
    @GetMapping("/connect/{userId}")
    public SseEmitter connect(@PathVariable String userId) throws IOException {
        return SSEServer.connect(userId);
    }

    /**
     * 推送给所有人
     *
     * @param message
     * @return
     */
    @GetMapping("/push/{message}")
    public ResponseEntity<String> push(@PathVariable(name = "message") String message) {
        SSEServer.batchSendMessage(message);
        return ResponseEntity.ok("WebSocket 推送消息给所有人");
    }

    /**
     * 发送给单个人
     *
     * @param message
     * @param userid
     * @return
     */
    @GetMapping("/push_one/{message}/{userid}")
    public ResponseEntity<String> pushOne(@PathVariable(name = "message") String message,
                                          @PathVariable(name = "userid") String userid) {
        SSEServer.sendMessage(userid, message);
        return ResponseEntity.ok("WebSocket 推送消息给" + userid);
    }

    /**
     * 关闭连接
     */
    @GetMapping("/close/{userid}")
    public ResponseEntity<String> close(@PathVariable("userid") String userid) {
        SSEServer.removeUser(userid);
        return ResponseEntity.ok("连接关闭");
    }

    // http://localhost:8888/user/test  先连接sse
    // http://localhost:8888/sse/upload/userId // 然后发起文件上传请求
    @GetMapping("/upload/{userId}")
    public ResponseEntity<String> upload(@PathVariable String userId) {
        new Thread(() -> {
            ThreadUtil.sleep(5 * 1000); // 线程睡眠 5 秒
            SSEServer.sendMessage(userId, "文件上传成功,请查看!");
            System.out.println("文件上传结束");
        }, "T1").start();
        return ResponseEntity.ok("文件上传请求成功！");
    }

}